﻿using Microsoft.SqlServer.Server;
using System;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;

namespace SqlServerExtLib_2008
{
    public class CommonFn
    {
        
        [SqlFunction(
            DataAccess = DataAccessKind.Read, 
            IsDeterministic = true, 
            Name = "IsMatch")]
        public static bool IsMatch(SqlString input, SqlString pattern, SqlString options)
        {
            if (input.IsNull)
            {
                return false;
            }

            if (pattern.IsNull)
            {
                throw new SqlNullValueException("[pattern] 不能是 NULL");
            }

            RegexOptions regexOptions = RegexOptions.None;

            if (!options.IsNull)
            {
                string strOptions = options.ToString();
                if (strOptions.Contains("i"))
                {
                    regexOptions |= RegexOptions.IgnoreCase;
                }

                if (strOptions.Contains("m"))
                {
                    regexOptions |= RegexOptions.Multiline;
                }
            }

            return Regex.IsMatch(input.ToString(), pattern.ToString(), regexOptions);
        }
    }
}
